﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;

namespace Common
{

    public class JwtModel
    {
      
        public long Uid { get; private set; }
        public List<long> RoleIds { get;private set; }
        public List<long> Permissions { get; private set; }

        public JwtModel(long uid,List<long> roleIds,List<long> permissions)
        {
            this.Uid = uid;
            this.RoleIds = roleIds;
            this.Permissions = permissions;
        }
    }
    public class JwtHelper
    {
        /// <summary>
        /// 创建jwt
        /// </summary>
        /// <param name="model">用户的一些信息 通过jwt传递的</param>
        /// <returns></returns>
        public static string CreateJwt(JwtModel model)
        {
            // 装备jwt的信息
            var iss = Appsettings.app("Authentication", "Issuer");
            var aud = Appsettings.app("Authentication", "Audience");
            var secret = Appsettings.app("Authentication", "Secret");
            var exp = Appsettings.app("Authentication", "Exp").ToInt32();//过期时间
            var claims = new List<Claim>()
            {
                new Claim(JwtRegisteredClaimNames.Jti,model.Uid.ToString()),
                new Claim(JwtRegisteredClaimNames.Iat,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddSeconds(exp)).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Iss,iss),
                new Claim(JwtRegisteredClaimNames.Aud,aud)
            };
            // 角色
            claims.AddRange(model.RoleIds.Select(p=>new Claim(ClaimTypes.Role,p.ToString())));
            //权限
            claims.AddRange(model.Permissions.Select(p=> new Claim("Permission",p.ToString())));
            // 构建秘钥
            var key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secret));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            // 构建jwt
            var jwt = new JwtSecurityToken(issuer: iss, claims: claims, signingCredentials: creds);
            var jwtHandler = new JwtSecurityTokenHandler();
            var encodedjwt = jwtHandler.WriteToken(jwt);
            return encodedjwt;
        }
        /// <summary>
        /// 校验token
        /// </summary>
        /// <param name="token"></param>
        public static bool CheckToken(string token)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            var secret = Appsettings.app("Authentication", "Secret"); ;
            var keyByteArray = Encoding.ASCII.GetBytes(secret);
            var signingKey = new SymmetricSecurityKey(keyByteArray);
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

            var jwt = jwtHandler.ReadJwtToken(token);
            return jwt.RawSignature == Microsoft.IdentityModel.JsonWebTokens.JwtTokenUtilities.CreateEncodedSignature(jwt.RawHeader + "." + jwt.RawPayload, signingCredentials);

        }
        /// <summary>
        /// 解析token
        /// </summary>
        /// <param name="jwtStr"></param>
        /// <returns></returns>
        public static JwtSecurityToken SerializeJwt(string jwtStr)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            // token校验
            if (!string.IsNullOrWhiteSpace(jwtStr) && jwtHandler.CanReadToken(jwtStr))
            {

                JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);

                return jwtToken;
            }

            return null;
        }
    }
}
